//
//  PublickFunctionObject.m
//  XinLiJianKangJiaoYu
//
//  Created by 李文强 on 2018/12/4.
//  Copyright © 2018 sijiaokeji. All rights reserved.
//

#import "PublickFunctionObject.h"

@implementation PublickFunctionObject
+(CGSize)getLabelWith:(UILabel *)label{
    NSString *str = label.text;
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = label.font;
    CGSize size = [str boundingRectWithSize:CGSizeMake( MAXFLOAT,label.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    return size;
}
+(CGSize)getLabelHeight:(UILabel *)label{
    NSString *str = label.text;
    label.numberOfLines = 0;
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = label.font;
    CGSize size = [str boundingRectWithSize:CGSizeMake(label.frame.size.width,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    return size;
}
+(CGSize)getStringSize:(NSString *)str andFondSize:(float)fond{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:fond];
    CGSize size = [str boundingRectWithSize:CGSizeMake(APP_WIDTH-20,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
    return size;
}

+ (BOOL)isX{
    if (@available(iOS 11.0, *)) {
       // 利用safeAreaInsets.bottom > 0.0来判断是否是iPhone X以上设备。
       UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
       if (window.safeAreaInsets.bottom > 0.0) {
          
           return YES;
          } else {
              return NO;
          }
        } else {
            return YES;
    }
}
//获得当前时间戳
+(NSString *)getTimeSpan:(NSString *)time_type{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    if (time_type.length == 0||time_type == nil) {
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    }else{
        [formatter setDateFormat:time_type];
    }
     // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}
+(NSString *)getTimeCurrent{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月"];
    NSString *dateString       = [formatter stringFromDate:[NSDate date]];
    return dateString;
}
#pragma mark - 将某个时间转化成 时间戳
+(NSString *)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
  //  NSLog(@"将某个时间转化成 时间戳&&&&&&&timeSp:%ld",(long)timeSp); //时间戳的值
    return [NSString stringWithFormat:@"%ld",(long)timeSp];
}
//计算键盘剩余高度
+(CGFloat)getHideHight:(CGFloat)viewH andKeyBordHight:(CGFloat)keyBordHight{
    CGFloat lostH = APP_HEIGHT-viewH;
    CGFloat moveH = 0.00;
    if (keyBordHight>lostH) {
        moveH = keyBordHight-lostH;
    }else{
        
    }
    return moveH;
}
//正则手机号
+(BOOL)checkPhone:(NSString *)phone{
    NSString *regex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regex options:NSRegularExpressionCaseInsensitive error:&error];
    if (error) return NO;
    NSInteger count = [regular numberOfMatchesInString:phone options:NSMatchingReportCompletion range:NSMakeRange(0, phone.length)];
    if (count > 0) {
        return YES;
    } else {
        return NO;
    }
}
+ (NSString *)eduteMoth:(int)m{
    switch (m) {
        case 1:
        {
            return @"一月";
        }
            break;
        case 2:
        {
            return @"二月";
        }
            break;
        case 3:
        {
            return @"三月";
        }
            break;
        case 4:
        {
            return @"四月";
        }
            break;
        case 5:
        {
            return @"五月";
        }
            break;
        case 6:
        {
            return @"六月";
        }
            break;
        case 7:
        {
            return @"七月";
        }
            break;
        case 8:
        {
            return @"八月";
        }
            break;
        case 9:
        {
            return @"九月";
        }
            break;
        case 10:
        {
            return @"十月";
        }
            break;
        case 11:
        {
            return @"十一月";
        }
            break;
        case 12:
        {
            return @"十二月";
        }
            break;
        default:
            break;
    }
    return @"一月";
}
+(NSString *)convertToJsonData:(NSDictionary *)dict

{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
//支付宝支付
//+ (void)aliPayFunction:(NSDictionary *)parama{
#pragma mark - 支付宝测试
//    //将商品信息拼接成字符串
//    NSString *orderInfo = [parama objectForKey:@"RequiredParameter"];
//    NSLog(@"orderSpec = %@",orderInfo);
//    NSString *appScheme = @"alisdkdemo";
//    [[AlipaySDK defaultService] payOrder:orderInfo fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//        NSLog(@"reslut = %@",resultDic);
//    }];
//}
//Wechart支付
//+ (void)weChartPayFunction:(NSDictionary *)parama{
//    NSString * jsonStr = [parama objectForKey:@"RequiredParameter"];
//    NSLog(@"得到微信支付strr %@",jsonStr);
//    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
//    NSError *err;
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
//    NSLog(@"得到微信支付strr %@",dic);
//#pragma mark - 微信支付
//    // 设置好后再调用 判断是否安装微信
//    // 判断是否安装微信
//    if ([WXApi isWXAppInstalled] ){
//        //判断当前微信的版本是否支持OpenApi
//        if ([WXApi isWXAppSupportApi]) {
//            //调起微信支付
//            PayReq *request = [[PayReq alloc] init];
//            request.partnerId = [dic objectForKey:@"partnerid"];
//            request.prepayId= [dic objectForKey:@"prepayid"];
//            request.package = [dic objectForKey:@"package"];
//            request.nonceStr= [dic objectForKey:@"noncestr"];
//            request.timeStamp = [[dic objectForKey:@"timestamp"] intValue];
//            request.sign= [dic objectForKey:@"sign"];
//            [WXApi sendReq:request];
//        }else{
//            //调起微信支付
//            PayReq *request = [[PayReq alloc] init];
//            request.partnerId = [dic objectForKey:@"partnerid"];
//            request.prepayId= [dic objectForKey:@"prepayid"];
//            request.package = [dic objectForKey:@"package"];
//            request.nonceStr= [dic objectForKey:@"noncestr"];
//            request.timeStamp = [[dic objectForKey:@"timestamp"] intValue];
//            request.sign= [dic objectForKey:@"sign"];
//            [WXApi sendReq:request];
//        }
//    }
//}
//url请求
+ (void)postFunction:(NSDictionary *)parama andUrl:(NSString *)url andGetDataSuccess:(GetDataDuccess)success andFailed:(GetDataFailed)failed{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    NSString *token = TOKEN;
//    if (token.length>0) {
//        [manager.requestSerializer setValue:token forHTTPHeaderField:@"Token"];
//    }
    [manager POST:url parameters:parama progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSString *Code = [responseObject objectForKey:@"Code"];
//        if ([Code intValue] == -7) {
//            //重新登录获取新的Token
//            NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:@"COUNT"];
//            NSString *pass = [[NSUserDefaults standardUserDefaults]objectForKey:@"PASS"];
//            NSString *time = [PublickFunctionObject getTimeSpan:@" "];
//            NSString *url = [NSString stringWithFormat:@"%@%@",BASEURL,LOGINURL];
//            NSDictionary *dic = @{@"UserName":name,
//                                      @"Password":[NSString md5:pass],
//                                      @"TimeSpan":time};
//            [manager POST:url parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
//            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                NSArray *array = [responseObject objectForKey:@"LoginInfoDto"];
//                //存储TOKEN
//                NSString *getToken = [responseObject objectForKey:@"Token"];
//                NSString *token = getToken;
//                [[NSUserDefaults standardUserDefaults]setValue:token forKey:@"TOKEN"];
//                if ([[responseObject objectForKey:@"Code"] intValue]==1) {
//                    //成功
//                    LoginModel *model = [LoginModel yy_modelWithJSON:array[0]];
//                    [[NSUserDefaults standardUserDefaults]setValue:model.AccountID forKey:@"TACCOUNTID"];
//                    [[NSUserDefaults standardUserDefaults]setValue:model.UserSig forKey:@"TUSERSIG"];
//                    [[NSUserDefaults standardUserDefaults]setValue:model.AccountID forKey:@"ACCOUNTID"];
//                }
//                [self postFunction:parama andUrl:url andGetDataSuccess:^(id responseBody) {
//                    
//                } andFailed:^(NSString *error) {
//                    
//                }];
//            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                NSLog(@"错误 %@",error);
//            }];
//        }else if ([Code intValue]==1){
//            success(responseObject);
//        }else{
//            [XSInfoView showInfo:[responseObject objectForKey:@"Message"] onView:[UIApplication sharedApplication].keyWindow.rootViewController];
//            failed(@"请求错误");
//        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"错误 %@",error);
        failed(@"请求错误");
         [XSInfoView showInfo:@"请求失败" onView:[UIApplication sharedApplication].keyWindow.rootViewController];
    }];
}
//富文本
+ (NSMutableAttributedString *)getPriceAttribute:(NSString *)string and:(UIColor *)color andChangeBenginString:(NSString *)beginString andEndString:(NSString *)endString andSize:(int)font{
    
    NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:string];
    //目的是想改变 ‘/’前面的字体的属性，所以找到目标的range
    NSRange range1 = [string rangeOfString:beginString];
    NSRange range2;
    NSRange pointRange;
    if (endString.length == 0) {
       pointRange = NSMakeRange(range1.location+1, string.length-range1.location-1);
    }else{
        range2 = [string rangeOfString:endString];
        pointRange = NSMakeRange(range1.location, range2.location-range1.location);
    }
    [attribut addAttribute:NSForegroundColorAttributeName value:color range:pointRange];
    //赋值
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[NSFontAttributeName] = [UIFont systemFontOfSize:font];
    [attribut addAttributes:dic range:pointRange];
    return attribut;
}
#pragma mark - 压缩图片
+ (UIImage *)zipPicture:(UIImage *)image{
    CGFloat compression = 1;
    CGFloat maxLength = 1024*10;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    return resultImage;
}
#pragma mark--日期选为本月第一天和最后一天算法

+ (NSString *)getMonthBeginWith:(NSString *)dateStr{
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd"];
    NSDate *newDate=[format dateFromString:dateStr];
    double interval = 0;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setFirstWeekday:2];//设定周一为周首日
    [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&newDate interval:&interval forDate:newDate];
    NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    
    [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *beginString = [myDateFormatter stringFromDate:newDate];
    
    return beginString;
    
}

+ (NSString *)getMonthEndWith:(NSString *)dateStr{
     NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"YYYY-MM-dd"];
    NSDate *newDate=[format dateFromString:dateStr];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    NSString *newTime = [NSString stringWithFormat:@"%@-%@-%lu",[dateStr componentsSeparatedByString:@"-"][0],[dateStr componentsSeparatedByString:@"-"][1],(unsigned long)numberOfDaysInMonth];
    NSDate *date = [format dateFromString:newTime];
    double interval = numberOfDaysInMonth;
    [calendar setFirstWeekday:2];//设定周一为周首日
//    [calendar rangeOfUnit:NSMonthCalendarUnit startDate:&newDate interval:&interval forDate:newDate];
    [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&date interval:&interval forDate:date];
    
   NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
    
   [myDateFormatter setDateFormat:@"YYYY-MM-dd"];
    
   NSString *endString = [myDateFormatter stringFromDate:newDate];
    
   return endString;
    
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(error) {
        NSLog(@"json解析失败：%@",error);
        return nil;
    }
     return dic;
}
+ (CGFloat)currentScreenSize:(int)type{
    if (type == 1) {
        //大屏幕
        return MAINWMAX;
    }else{
        //小屏幕
        return MAINW;
    }
}
#pragma mark - 通知变更界面
+ (void)changeMainView:(NSString *)noticeName AndType:(BOOL)type{
    if (type == NO) {
        [[NSNotificationCenter defaultCenter]postNotificationName:noticeName object:nil userInfo:@{@"Type":@"1"}];
    }else{
        [[NSNotificationCenter defaultCenter]postNotificationName:noticeName object:nil userInfo:@{@"Type":@"0"}];
    }
}

#pragma mark - 数据持久化存储-数组转换成Data
+ (void)saveArrayForData:(NSMutableArray *)array forKey:(NSString *)key{
    NSMutableArray *copeArray = [array mutableCopy];//深拷贝数组文件
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:copeArray];
    [USERDEFAL setObject:data forKey:key];
}
#pragma mark - 数据持久化解码-Data转换成数组
+ (NSMutableArray *)getArrayForDataForKey:(NSString *)key{
    NSData *data = [USERDEFAL objectForKey:key];
    NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return array;
}
@end
